<template>
  <div class="form__wrapper">
      <el-form :model="formData" ref="form" label-width="100px" class="demo-dynamic">
        <el-form-item
          prop="orderId"
          label="相关订单"
          :rules="[
            { required: true, message: '相关订单不能为空', trigger: ['blur', 'change'], type: 'number' },
          ]"
        >
          <el-select v-model="formData.orderId" filterable>
            <el-option
              v-for="(p, i) in orderOpts"
              :key="i"
              :label="`${p.orderName}(${ p.orderCode})`"
              :value="p.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="batch"
          label="批次"
          :rules="[
            { required: true, message: '批次不能为空', trigger: ['blur', 'change'] },
            { max: 50, message: '批次不能超过50个字符', trigger: ['blur', 'change'] },
          ]"
        >
          <el-input v-model="formData.batch" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item
          prop="position"
          label="仓位"
          :rules="[
            { required: true, message: '仓位不能为空', trigger: ['blur', 'change'] },
            { max: 50, message: '仓位不能超过50个字符', trigger: ['blur', 'change'] },
          ]"
        >
          <el-input v-model="formData.position" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item
          prop="recipient"
          label="签收人"
          :rules="[
            { required: true, message: '签收人不能为空', trigger: ['blur', 'change'] },
            { max: 50, message: '签收人不能超过50个字符', trigger: ['blur', 'change'] },
          ]"
        >
          <el-input v-model="formData.recipient" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item
          v-for="(device, index) in formData.deviceList"
          :label="'产品' + (index + 1)"
          :key="device.key"
          :rules="[
            { required: true, message: '产品不能为空', trigger: ['blur', 'change'], type: 'number' },
          ]"
        >
          <div class="production_wrapper">

            <el-form-item
              :prop="'deviceList.' + index + '.productId'"
              :rules="[
                { required: true, message: '产品不能为空', trigger: ['blur', 'change'], type: 'number' },
              ]"
            >
            <el-select v-model="device.productId" @change="handleProductIdChange">
              <el-option
                v-for="(p, i) in productionOpts"
                :key="i"
                :label="p.name"
                :value="p.id"
                :disabled="disabledProductionIdList.includes(p.id)"
              ></el-option>
            </el-select>
          </el-form-item>
            <el-form-item
              :prop="'deviceList.' + index + '.huIds'"
              :rules="[
                { required: true, message: 'HUID不能为空', trigger: ['blur', 'change'] },
              ]"
            >
            <el-input type="textarea" v-model="device.huIds" placeholder="设备HUID，ID之间请以 , 分隔" ></el-input>
            </el-form-item>
            <el-button class="deleteButton" @click.prevent="removeProduction(device)" size="mini" type="danger">删除</el-button>

          </div>

        </el-form-item>
        <el-form-item>
          <el-button @click="appendProduction" class="appendButton" plain>添加产品</el-button>
        </el-form-item>
      </el-form>
    <div class="actions">
      <el-button type="primary" size="small" @click="submit" :loading="submitLoading">提交</el-button>
      <el-button type="default" size="small" @click="cancel" :disabled="submitLoading">取消</el-button>
    </div>
  </div>
</template>

<script>

import { dict_productionType } from '@/utils/dictionary'

import { createApi } from '@/api/modules/warehouse/in'
import { dict_orderApi, dict_productionApi } from '@/api/modules/dictionary'

export default {
  name: 'InWarehouseCreate',
  data () {
    return {
      orderOpts: [],
      productionOpts: [],
      disabledProductionIdList: [], // 存放禁用的产品ID，用户选择后，设置为禁用，防止重复选择
      
      formData: {
        deviceList: [
          {
            productId: null,
            huIds: '',
            key: Date.now()
          }
        ],
        manufacturer: ''
      },


      submitLoading: false
    }
  },
  methods: {
    async getOrderOpts () {
      try {
        const { data } = await dict_orderApi()
        this.orderOpts = data
      } catch (err) {}
    },
    async getProductionOpts () {
      try {
        const { data } = await dict_productionApi()
        this.productionOpts = data
      } catch (err) {}
    },

    
    submit () {
      
      this.$refs['form'].validate(async valid => {
        if(valid) {
          try {
            this.submitLoading = true
            const params = {
              ...this.formData
            }
            
            // 处理huIds
            params.deviceList.forEach(device => {
              device.huId = device.huIds.split(/[,，]/) // 切割
              device.huId = device.huId.filter(item => (item ?? '') !== '') // 过滤掉空字符串
              device.huId = [...new Set(device.huId)] // 去重
            })
            
            await createApi(params)
            this.$message({ type: 'success', message: '添加成功' })
            this.$emit('success')
          } catch (err) {
            console.error(err)
          }
          this.submitLoading = false
        }
      })
    },
    cancel () {
      this.$emit('close')
    },


    removeProduction(item) {
      if(this.formData.deviceList.length < 2) {
        this.$message.warning('请至少输入一个设备')
        return
      }
      var index = this.formData.deviceList.indexOf(item)
      if (index !== -1) {
        this.formData.deviceList.splice(index, 1)
      }
      this.updateDisabledProductionIdList()
    },
    appendProduction() {
      this.formData.deviceList.push({
        productId: null,
        huIds: '',
        key: Date.now()
      })
    },
    handleProductIdChange() {
      this.updateDisabledProductionIdList()
    },
    // 更新禁用的产品ID
    updateDisabledProductionIdList () {
      const disabledProductionIdList = []
      this.formData.deviceList.forEach(production => {
        disabledProductionIdList.push(production.productId)
      })
      this.disabledProductionIdList = disabledProductionIdList
    },
  },
  mounted () {
    this.getOrderOpts()
    this.getProductionOpts()
  }
}
</script>

<style lang="less" scoped>
@import '../../../styles/form.less';

.form__wrapper {
  .el-form, .actions {
    max-width: 600px;
    .el-form-item {
      position: relative;

      .production_wrapper {
        .el-textarea {
          margin-top: 4px;
        }
        .deleteButton {
          position: absolute;
          right: -70px;
          top: 6px;

        }
      }

      .el-select {
        width: 100%;
      }
      .appendButton {
        width: 100%;
      }
    }
  }
}
</style>